﻿using Hangfire;
using BgWorks.Models;
using BgWorks.Works;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using BgWorks.Common;

namespace BgWorks.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ControlController : ControllerBase
    {

        public ControlController()
        {
             
        }

        /// <summary>
        /// 入参模板
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public string ExampleCorn()
        {
            string res = "";
            res += $"每天0点0分:{Cron.Daily(0, 0)},";
            res += $"每小时的30分执行:{Cron.Hourly(30)},";
            res += $"小时整点:{Cron.Hourly(0)},";
            res += $"整分钟:{Cron.Minutely()},";
            return res;
        }

        /// <summary>
        /// 入参模板
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public string ExampleApi()
        {
            JobData it = new JobData();
            it.url = "http://localhost:8095/";
            it.resource = "api/getToken";
            it.timeout = 5000;
            it.methodname = "get";
            it.value = "{data:'111'}";
            JobModel model = new JobModel();
            model.JobKey = "";
            model.Type = "API";
            model.Data = it;
            return Newtonsoft.Json.JsonConvert.SerializeObject(model);
        }

        /// <summary>
        /// 入参模板
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public string ExampleSql()
        {
            JobData it = new JobData();
            it.Sql = "insert into extapi_logs (log_id,log_date,log_message,message_id,process_result)values(Inoutseq.NEXTVAL,sysdate,1111,'hangfire中执行','测试')";
            it.Connectionkey = "HIS";
            it.ConnectionString = "Password=jhecis;User ID=jhecis;Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.103.155)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=DEVJHECIS)));";
            it.SqlType = "oracle";
            JobModel model = new JobModel();
            model.JobKey ="";
            model.Type = "SQL";
            model.Data = it;
            return Newtonsoft.Json.JsonConvert.SerializeObject(model);
        }

        /// <summary>
        /// dll入参模板
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public string ExampleDll()
        {
            JobData it = new JobData();
            it.DllName = "LisTest.dll";
            it.DllSpace = "LisTest.LisClass";
            it.DllMethod = "TestLis";
            it.Args = "itemid123";
            JobModel model = new JobModel();
            model.JobKey = "";
            model.Type = "DLL";
            model.Data = it;
            model.CronStr= Cron.Minutely();
            return Newtonsoft.Json.JsonConvert.SerializeObject(model);
        }

        /// <summary>
        ///  创建立即单次任务
        /// </summary>
        /// <param name="jobModel"></param>
        /// <returns></returns>
        [HttpPost]
        public JobModel Once([FromBody] JobModel jobModel)
        {
            IWork work = GetWork(jobModel);
            if (work != null)
            {
                string key = BackgroundJob.Enqueue(() => work.WorkThing(jobModel));
                jobModel.JobKey = key;
            }
            return jobModel;
        }
        /// <summary>
        ///  创建延时单次任务
        /// </summary>
        /// <param name="jobModel"></param>
        /// <returns></returns>
        [HttpPost]
        public JobModel DelayOnce([FromBody] JobModel jobModel)
        {
            string key = BackgroundJob.Schedule(() => Console.WriteLine("只执行一次!"), TimeSpan.FromDays(1));
            jobModel.JobKey = key;
            return jobModel;
        }

        private IWork GetWork(JobModel jobModel)
        {
            if (jobModel.Type?.ToUpper() == "API")
            {
                return new APIWork();
            }
            else if (jobModel.Type?.ToUpper() == "SQL")
            {
                return new SqlWork();
            }
            else if (jobModel.Type?.ToUpper() == "DLL")
            {
                return new DllWork();
            }
            return null;
        }

        /// <summary>
        ///  创建一个周期执行任务
        /// </summary>
        /// <param name="jobModel"></param>
        /// <returns></returns>
        [HttpPost]
        public JobModel AddTimer([FromBody] JobModel jobModel)
        {
            IWork work = GetWork(jobModel);
            if (work != null)
            {
                jobModel.JobKey = Guid.NewGuid().ToString();
                RecurringJob.AddOrUpdate(jobModel.JobKey, () => work.WorkThing(jobModel), jobModel.CronStr, TimeZoneHelper.Instance().GetTimeZone());
            }
            return jobModel;
        }

        [HttpPost]
        /// <summary>
        /// 移除一个周期任务，通过实体中的key
        /// </summary>
        /// <param name="jobModel"></param>
        /// <returns></returns>
        public JobModel RemoveTimer([FromBody] JobModel jobModel)
        {
            //如果存在就删除周期任务
            if (!string.IsNullOrEmpty(jobModel.JobKey))
            {
                RecurringJob.RemoveIfExists(jobModel.JobKey);
            }
            return jobModel;
        }

        [HttpGet]
        /// <summary>
        /// 移除一个周期任务，通过key
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string RemoveTimer([FromBody] string key)
        {
            RecurringJob.RemoveIfExists(key);
            return "";
        }

        [HttpPost]
        /// <summary>
        /// 手动触发执行一个周期任务，通过key
        /// </summary>
        /// <param name="jobModel"></param>
        /// <returns></returns>
        public JobModel TriggerTimer([FromBody] JobModel jobModel)
        {
            //如果存在就删除周期任务
            if (!string.IsNullOrEmpty(jobModel.JobKey))
            {
                RecurringJob.TriggerJob(jobModel.JobKey);
            }
            return jobModel;
        }

        [HttpGet]
        /// <summary>
        /// 手动触发执行一个周期任务，通过key
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string TriggerTimerByKey([FromBody] string key)
        {
            //如果存在就删除周期任务
            if (string.IsNullOrEmpty(key))
            {
                RecurringJob.TriggerJob(key);
            }
            return "";
        }
    }
}
